package com.example.carrierapp.ui.pop;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.carrierapp.event.ProvinceBean;
import com.example.carrierapp.ui.adapter.CityChooseAdapter;
import com.example.carrierapp.util.SPUtils;
import com.example.carrierapp.util.ToastUtils;
import com.example.lb.fingerdemo.R;

import java.util.ArrayList;
import java.util.List;

/**
 * PopupWindow弹出框
 */

@SuppressWarnings("unused")
public class CitySelectPopup implements View.OnClickListener {

    private Activity mActivity;
    private Context mContext;
    private LayoutInflater mInflater;
    private PopupWindow mPopupWindow;
    private List<ProvinceBean> mList;

    private int mProvincePosition;
    private int mCityPosition;

    //当前城市及ID
    private String mCurCity;
    private int mCurId;

    //获得适配器对象
    private CityChooseAdapter mProvinceAdapter;
    private CityChooseAdapter mCityAdapter;
    private CityChooseAdapter mBoroughsAdapter;
    private RecyclerView recyclerView;

    private int addresstp;

    //显示选中的城市名，返回上一级
    private TextView tv_select;
    private TextView tv_return;
    private TextView tv_cancel;

    private CityChooserListener mListener;

    LinearLayout ll_history;//历史栏布局
    //    private int mVisibility;//是否显示
    private Button bt_his1;
    private Button bt_his2;
    private Button bt_his3;
    private List<String> mStartCities;
    private List<Integer> mStartId;
    private List<String> mEndCities;
    private List<Integer> mEndId;

    private int type;//0出发地 1目的地 2隐藏历史 3不能选择全国

    private StringBuffer stringBuffer;

    public CitySelectPopup(Activity activity, Context context, PopupWindow popupWindow, int type) {
        this.type = type;
        mActivity = activity;
        mContext = context;
        mPopupWindow = popupWindow;
        mInflater = LayoutInflater.from(mContext);
        stringBuffer = new StringBuffer();
    }


    public void showInParentDown(View v) {
        getPopupWindowInstance();
        if (v != null) {
            if (mPopupWindow != null) {
                mPopupWindow.showAsDropDown(v);
            }
        }
    }

    private void getPopupWindowInstance() {
        if (null == mPopupWindow) {
            initPopupWindow();
        }
    }

    private void initPopupWindow() {
        View popupWindow = mInflater.inflate(R.layout.activity_city_chooser, null);
        recyclerView = (RecyclerView) popupWindow.findViewById(R.id.rv_chooser);
        tv_cancel = (TextView) popupWindow.findViewById(R.id.tv_cancel);
        tv_select = (TextView) popupWindow.findViewById(R.id.tv_show_select);
        tv_return = (TextView) popupWindow.findViewById(R.id.tv_return);
        bt_his1 = (Button) popupWindow.findViewById(R.id.bt_his1);
        bt_his2 = (Button) popupWindow.findViewById(R.id.bt_his2);
        bt_his3 = (Button) popupWindow.findViewById(R.id.bt_his3);
        ll_history = (LinearLayout) popupWindow.findViewById(R.id.ll_history);
//        if (ll_history != null) {
//            ll_history.setVisibility(mVisibility);
//        }

        /**隐藏软键盘**/
        View view = mActivity.getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }

        switch (type) {
            case 0:
                if (mStartCities != null) {
                    if (mStartCities.size() > 0) {
                        ll_history.setVisibility(View.VISIBLE);
                    } else {
                        ll_history.setVisibility(View.GONE);
                    }
                }
                setHistoryCities("startCities", "startId");
                break;
            case 1:
                if (mEndCities != null) {
                    if (mEndCities.size() > 0) {
                        ll_history.setVisibility(View.VISIBLE);
                    } else {
                        ll_history.setVisibility(View.GONE);
                    }
                }
                setHistoryCities("endCities", "endId");
                break;
            case 2:
                ll_history.setVisibility(View.GONE);
                break;
            case 3:
                ll_history.setVisibility(View.GONE);
                break;
        }
        tv_return.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
        GridLayoutManager manager = new GridLayoutManager(mContext, 4);
        recyclerView.setLayoutManager(manager);
//        recyclerView.addItemDecoration(new GridDivider(mContext, 2, R.color.blac  k));

        if (mList == null) {
            mList = SPUtils.get(mContext,"Address");
            if (mList == null) {
                return;
            }
            ProvinceBean provinceBean = new ProvinceBean();
            provinceBean.setProvinceName("全国");
            provinceBean.setId(0);
            provinceBean.setCities(null);
            mList.add(0, provinceBean);
        }
        setListener(mList, recyclerView);
        mPopupWindow = new PopupWindow(popupWindow, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable(mContext.getResources(), (Bitmap) null));
    }


    private void setListener(List<ProvinceBean> list, RecyclerView recyclerView) {
        CityChooseAdapter adapter = new CityChooseAdapter(mContext, list);
        mProvinceAdapter = adapter;
        tv_return.setVisibility(View.GONE);
        recyclerView.setAdapter(adapter);
        adapter.setOnCityChooseItemListener(new CityChooseAdapter.OnCityItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                //省级监听
                if (type != 3) {
                    tv_select.setText(list.get(position).getProvinceName());
                    tv_return.setVisibility(View.VISIBLE);
                } else if (position != 0) {
                    tv_select.setText(list.get(position).getProvinceName());
                    tv_return.setVisibility(View.VISIBLE);
                }
                if (type == 2 || type == 3) {
                    if (!"全国".equals(list.get(position).getProvinceName())) {
                        stringBuffer.append(list.get(position).getProvinceName());
                    }
                }
//                TextView tv_recycleview_item = (TextView) view.findViewById(R.id.tv_city_item);
//                tv_recycleview_item.setTextColor(mContext.getResources().getColor(R.color.oringe_light));
                CityChooseAdapter cityChooseAdapter = new CityChooseAdapter(mContext, list);
                cityChooseAdapter.setAddressType(1);

                if (position != 0) {
                    cityChooseAdapter.setCityList(position);
                    mCityAdapter = cityChooseAdapter;
                    if (addresstp != 0) {
                        addresstp = 0;
                    }
                    addresstp = cityChooseAdapter.getAddressType();
                    recyclerView.setAdapter(cityChooseAdapter);
                    mProvincePosition = position;

                    cityChooseAdapter.setOnCityChooseItemListener(new CityChooseAdapter.OnCityItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            //市级监听
                            if (type == 2 || type == 3) {
                                if (!stringBuffer.toString().equals(list.get(mProvincePosition).getCities().get(position).getCityName())) {
                                    stringBuffer.append(list.get(mProvincePosition).getCities().get(position).getCityName());
                                }
                            }
                            tv_select.setText(list.get(mProvincePosition).getCities().get(position).getCityName());
                            CityChooseAdapter boroughsAdapter = new CityChooseAdapter(mContext, list);
                            boroughsAdapter.setAddressType(2);
                            mBoroughsAdapter = boroughsAdapter;
                            if (addresstp != 0) {
                                addresstp = 0;
                            }
                            addresstp = boroughsAdapter.getAddressType();
                            boroughsAdapter.setBoroughList(mProvincePosition, position);
                            Log.i("TAG", "addresstype:" + boroughsAdapter.getAddressType());
                            mCityPosition = position;
                            recyclerView.setAdapter(boroughsAdapter);
                            boroughsAdapter.setOnCityChooseItemListener(new CityChooseAdapter.OnCityItemClickListener() {
                                @Override
                                public void onItemClick(View view, int position) {
                                    //区级监听
                                    if (type == 2 || type == 3) {
                                        if (!"全部".equals(list.get(mProvincePosition).getCities().get(mCityPosition).getBoroughs().get(position).getBoroughName())) {
                                            stringBuffer.append(list.get(mProvincePosition).getCities().get(mCityPosition).getBoroughs().get(position).getBoroughName());
                                        }
                                    }
                                    tv_select.setText(list.get(mProvincePosition).getCities().get(mCityPosition).getBoroughs().get(position).getBoroughName());
                                    boroughsAdapter.setBoroughsposition(mCityPosition, position);
                                    mCurCity = boroughsAdapter.mCurrentCity;
                                    mCurId = boroughsAdapter.mCurrentId;
                                    Log.i("TAG", "当前城市：" + mCurCity + "----------当前城市ID：" + mCurId);
                                    if (mListener != null) {
                                        if (type == 2 || type == 3) {
                                            mListener.setCityName(stringBuffer.toString(), mCurId);
                                        } else {
                                            mListener.setCityName(mCurCity, mCurId);
                                        }
                                        switch (type) {
                                            case 0:
                                                getHistoryCities("startCities", "startId");
                                                break;
                                            case 1:
                                                getHistoryCities("endCities", "endId");
                                                break;
                                            case 2:
                                                break;
                                        }
                                    }
                                    closePopupWindow();
                                }
                            });

                        }
                    });
                } else {
                    if (type != 3) {
                        mProvinceAdapter.setProvincePosition(position);//当位置为第一个时，选中地址提交
                        mCurCity = mProvinceAdapter.mCurrentCity;
                        mCurId = mProvinceAdapter.mCurrentId;
                        if (mListener != null) {
                            mListener.setCityName(mCurCity, mCurId);
                            switch (type) {
                                case 0:
                                    getHistoryCities("startCities", "startId");
                                    break;
                                case 1:
                                    getHistoryCities("endCities", "endId");
                                    break;
                                case 2:
                                    break;
                            }

                        }
                        closePopupWindow();
                    } else {
                        ToastUtils.showCenterToast(mActivity,"出发地不能选择全国");
//                        Toast.makeText(mContext,"出发地不能选择全国",Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
    }

    /**
     * 获取历史城市
     */
    private void getHistoryCities(String citiesKey, String idKey) {
        List<String> cities = null;
        List<Integer> id = null;
        if (cities == null) {
            cities = new ArrayList<String>();
        }
        if (id == null) {
            id = new ArrayList<Integer>();
        }
        if (SPUtils.get(mContext,citiesKey) != null) {
            cities.addAll(SPUtils.get(mContext,citiesKey));
            id.addAll(SPUtils.get(mContext,idKey));
        }

        int count = 0;
        if (cities.size() == 0) {
            cities.add(0, mCurCity);
            id.add(0, mCurId);
        } else if (cities.size() < 3) {
            for (int i = 0; i < cities.size(); i++) {
                if (!cities.get(i).equals(mCurCity)) {
                    count++;
                } else {
                    break;
                }
                if (count == cities.size()) {
                    cities.add(0, mCurCity);
                    id.add(0, mCurId);
                    break;
                }
            }
        } else if (cities.size() == 3) {
            for (int i = 0; i < cities.size(); i++) {
                Log.i("TAG", cities.get(i) + "===================================");
                if (!cities.get(i).equals(mCurCity)) {
                    count++;
                } else {
                    break;
                }
                if (count == cities.size()) {
                    cities.remove(2);
                    id.remove(2);
                    cities.add(0, mCurCity);
                    id.add(0, mCurId);
                    break;
                }
            }
        } else if (cities.size() > 3) {
            for (int i = 0; i < cities.size() - 3; i++) {
                cities.remove(cities.size() - 1);
                id.remove(id.size() - 1);
            }
        }
        SPUtils.save(mContext,citiesKey, cities);
        SPUtils.save(mContext,idKey, id);
    }

    /**
     * 设置历史城市
     */
    private void setHistoryCities(String citiesKey, String idKey) {
        List<String> Cities = SPUtils.get(mContext,citiesKey);
        List<Integer> Id = SPUtils.get(mContext,idKey);
        if (Cities != null) {
            switch (Cities.size()) {
                case 0:
                    ll_history.setVisibility(View.GONE);
                    break;
                case 1:
                    ll_history.setVisibility(View.VISIBLE);
                    bt_his1.setVisibility(View.VISIBLE);
                    bt_his2.setVisibility(View.GONE);
                    bt_his3.setVisibility(View.GONE);
                    bt_his1.setText(Cities.get(0));
                    bt_his1.setOnClickListener(this);
                    break;
                case 2:
                    ll_history.setVisibility(View.VISIBLE);
                    bt_his1.setVisibility(View.VISIBLE);
                    bt_his2.setVisibility(View.VISIBLE);
                    bt_his3.setVisibility(View.GONE);
                    bt_his1.setText(Cities.get(0));
                    bt_his2.setText(Cities.get(1));
                    bt_his1.setOnClickListener(this);
                    bt_his2.setOnClickListener(this);
                    break;
                case 3:
                    ll_history.setVisibility(View.VISIBLE);
                    bt_his1.setVisibility(View.VISIBLE);
                    bt_his2.setVisibility(View.VISIBLE);
                    bt_his3.setVisibility(View.VISIBLE);
                    bt_his1.setText(Cities.get(0));
                    bt_his2.setText(Cities.get(1));
                    bt_his3.setText(Cities.get(2));
                    bt_his1.setOnClickListener(this);
                    bt_his2.setOnClickListener(this);
                    bt_his3.setOnClickListener(this);
                    break;
            }
        }
    }

    /**
     * 关闭popupwindow
     */
    public void closePopupWindow() {
        if (null != mPopupWindow && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (type) {
            case 0:
                if (SPUtils.get(mContext,"startCities") != null) {
                    mStartCities = SPUtils.get(mContext,"startCities");
                    mStartId = SPUtils.get(mContext,"startId");
                }
                break;
            case 1:
                if (SPUtils.get(mContext,"endCities") != null) {
                    mEndCities = SPUtils.get(mContext,"endCities");
                    mEndId = SPUtils.get(mContext,"endId");
                }
                break;
            case 2:
                break;
        }

        switch (v.getId()) {
            case R.id.tv_cancel:
                closePopupWindow();
                break;
            case R.id.tv_return:
                if (recyclerView != null) {
                    if (addresstp == 1) {
                        recyclerView.setAdapter(mProvinceAdapter);
                        tv_return.setVisibility(View.GONE);
                    } else if (addresstp == 2) {
                        recyclerView.setAdapter(mCityAdapter);
                        addresstp = 1;
                    }
                }
                break;
            case R.id.bt_his1:
                if (mListener != null) {
                    switch (type) {
                        case 0:
                            mListener.setCityName(mStartCities.get(0), mStartId.get(0));
                            break;
                        case 1:
                            mListener.setCityName(mEndCities.get(0), mEndId.get(0));
                            break;
                        case 2:
                            break;
                    }

                }
                closePopupWindow();
                break;
            case R.id.bt_his2:
                if (mListener != null) {
                    switch (type) {
                        case 0:
                            mListener.setCityName(mStartCities.get(1), mStartId.get(1));
                            break;
                        case 1:
                            mListener.setCityName(mEndCities.get(1), mEndId.get(1));
                            break;
                        case 2:
                            break;
                    }
                }
                closePopupWindow();
                break;
            case R.id.bt_his3:
                if (mListener != null) {
                    switch (type) {
                        case 0:
                            mListener.setCityName(mStartCities.get(2), mStartId.get(2));
                            break;
                        case 1:
                            mListener.setCityName(mEndCities.get(2), mEndId.get(2));
                            break;
                        case 2:
                            break;
                    }
                }
                closePopupWindow();
                break;
        }
    }


    public interface CityChooserListener {
        void setCityName(String cityName, int id);
    }

    public void setCityChooserListener(CityChooserListener listener) {
        mListener = listener;
    }
}
